import uuid

import oss2

from models import Image, ImageVersion, UserVIP, VIPPackage
from flask import request, jsonify, abort
from datetime import datetime, timedelta
from models import db, Admin, AdminAction, User, UserCollect, CollectItem, UserAction
import requests
from passlib.hash import argon2

auth = oss2.Auth('LTAI5tSSsZreQros8dcchrTe', 'dKoToq83nsV1xMTJN9VwIiryzKOkhg')
endpoint = "https://oss-cn-beijing.aliyuncs.com"
bucketName = "mjseed-code-image"
bucket = oss2.Bucket(auth, endpoint, bucketName)

# 管理员权限验证装饰器
def admin_required(f):
    def wrapper(*args, **kwargs):
        # admin_id = request.headers.get('X-Admin-ID')
        admin_id = 1    #测试阶段，硬编码为1号管理员
        admin = Admin.query.get(admin_id)
        if not admin:
            abort(401, '管理员未认证')
        return f(*args, **kwargs)

    wrapper.__name__ = f.__name__
    return wrapper


def generate_unique_filename(original_filename):
    # 获取文件扩展名
    file_extension = original_filename.split('.')[-1]
    # 生成唯一标识符
    unique_id = uuid.uuid4().hex
    # 当前时间戳
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    # 组合唯一文件名
    unique_filename = f"{timestamp}_{unique_id}.{file_extension}"
    return unique_filename



# 查看所有的照片表


def get_all_images():
    """
    获取所有已发布图片
    """
    try:
        # 查询 Image 和 ImageVersion 表的数据
        images = Image.query.join(ImageVersion, Image.image_id == ImageVersion.image_id).filter(
            ImageVersion.audit_status == 'approved'
        ).all()

        result = []
        for img in images:
            # 获取 ImageVersion 的数据
            version = ImageVersion.query.filter_by(image_id=img.image_id).first()
            name = version.oss_path.split('mjseed-code-image/', 1)[-1]
            oss_path = f'https://mjseed-code-image.oss-cn-beijing.aliyuncs.com/{name}'
            if version:
                result.append({
                    # Image 表的字段
                    'image_id': img.image_id,
                    'image_title': img.image_title,
                    'image_description': img.image_description,
                    'resolution': img.resolution,
                    'format': img.format,
                    'midjourney_code': img.midjourney_code,
                    'codecopy_time': img.codecopy_time,
                    'beliked': img.beliked,
                    'becollected': img.becollected,
                    'comment_time': img.comment_time,
                    'comment_context': img.comment_context,
                    'vip_exclusive': img.vip_exclusive,
                    'image_tag1': img.image_tag1,
                    'image_tag2': img.image_tag2,
                    'image_tag3': img.image_tag3,

                    # ImageVersion 表的字段
                    'version_id': version.version_id,
                    'admin_id': version.admin_id,
                    'audit_status': version.audit_status,

                    'oss_path': oss_path,
                    'upload_at': version.upload_at.isoformat() if version.upload_at else None,
                })
            else:
                result.append({
                    # Image 表的字段
                    'image_id': img.image_id,
                    'image_title': img.image_title,
                    'image_description': img.image_description,
                    'resolution': img.resolution,
                    'format': img.format,
                    'midjourney_code': img.midjourney_code,
                    'codecopy_time': img.codecopy_time,
                    'beliked': img.beliked,
                    'becollected': img.becollected,
                    'comment_time': img.comment_time,
                    'comment_context': img.comment_context,
                    'vip_exclusive': img.vip_exclusive,
                    'image_tag1': img.image_tag1,
                    'image_tag2': img.image_tag2,
                    'image_tag3': img.image_tag3,

                    # ImageVersion 表的字段
                    'version_id': None,
                    'admin_id': None,
                    'audit_status': None,
                    'oss_path': None,
                    'upload_at': None,
                    'vip_exclusive_version': None
                })

        return jsonify(result), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500






def get_image_by_id(image_id):
    """
    根据 image_id 获取单个已发布图片
    """
    try:
        # 查询 Image 和 ImageVersion 表的数据
        image = Image.query.get(image_id)
        if not image:
            return jsonify({'error': 'Image not found'}), 404

        # 获取 ImageVersion 的数据
        version = ImageVersion.query.filter_by(image_id=image.image_id).first()
        if not version:
            return jsonify({'error': 'ImageVersion not found'}), 404

        name = version.oss_path.split('mjseed-code-image/', 1)[-1]
        oss_path = f'https://mjseed-code-image.oss-cn-beijing.aliyuncs.com/{name}'

        result = {
            # Image 表的字段
            'image_id': image.image_id,
            'image_title': image.image_title,
            'image_description': image.image_description,
            'resolution': image.resolution,
            'format': image.format,
            'midjourney_code': image.midjourney_code,
            'codecopy_time': image.codecopy_time,
            'beliked': image.beliked,
            'becollected': image.becollected,
            'comment_time': image.comment_time,
            'comment_context': image.comment_context,
            'vip_exclusive': image.vip_exclusive,
            'image_tag1': image.image_tag1,
            'image_tag2': image.image_tag2,
            'image_tag3': image.image_tag3,

            # ImageVersion 表的字段
            'version_id': version.version_id,
            'admin_id': version.admin_id,
            'audit_status': version.audit_status,

            'oss_path': oss_path,
            'upload_at': version.upload_at.isoformat() if version.upload_at else None,
        }

        return jsonify(result), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

    #  上传新的照片


def upload_image():
    admin_id = 1  # 测试阶段，硬编码为1号管理员
    required_fields = [
        'title', 'description', 'resolution', 'format', 'midjourney_code',
        'vip_exclusive', 'tag1', 'tag2', 'tag3', 'audit_status'
    ]
    data = request.form
    required_fields1 = [
        'title', 'description', 'resolution', 'format', 'midjourney_code',
        'vip_exclusive', 'audit_status'
    ]
    if not all(field in data for field in required_fields1):
        return jsonify({'error': '缺少必要参数'}), 400

    try:
        # 上传文件
        image_file = request.files.get('file')
        if not image_file:
            return jsonify({'error': '未找到文件'}), 400

        # 获取文件名
        original_filename = image_file.filename
        unique_filename = generate_unique_filename(original_filename)

        # 上传文件到 OSS
        bucket.put_object(unique_filename, image_file)

        # 创建图片记录
        new_image = Image(
            image_title=data['title'],
            image_description=data['description'],
            resolution=data['resolution'],
            format=data['format'],
            midjourney_code=data.get('midjourney_code', {}),
            vip_exclusive=data['vip_exclusive'],
            image_tag1=data['tag1'],
            image_tag2=data['tag2'],
            image_tag3=data['tag3']
        )
        db.session.add(new_image)
        db.session.flush()  # 临时提交以获取自动生成的 image_id

        # 获取数据库生成的 image_id
        new_image_id = new_image.image_id

        # 创建版本记录
        oss_path = f"{bucketName}/{unique_filename}"
        new_version = ImageVersion(
            image_id=new_image_id,
            admin_id=admin_id,
            audit_status=data['audit_status'],
            oss_path=oss_path,
            vip_exclusive=data['vip_exclusive'],
            upload_at=datetime.now()
        )
        db.session.add(new_version)

        # 记录操作到 admin_action_db
        action = AdminAction(
            admin_id=admin_id,
            admin_operation='upload',
            operation_content=f"Uploaded image with ID: {new_image_id}, OSS Path: {oss_path}"
        )
        db.session.add(action)

        db.session.commit()
        return jsonify({'image_id': new_image_id}), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


#   管理员查看自己发布的照片
@admin_required
def get_images_by_admin(admin_id):
    """
    通过管理员ID获取其上传的所有图片及版本信息
    """
    try:
        # 获取当前操作的管理员
        current_admin_id = 1  # 测试阶段硬编码
        current_admin = Admin.query.get(current_admin_id)

        # 权限验证：非超级管理员只能查看自己的记录
        if current_admin.admin_right != 'super' and current_admin_id != admin_id:
            abort(403, '无权访问其他管理员的数据')

        # 联表查询：获取指定管理员的所有图片版本及关联图片
        query = db.session.query(Image, ImageVersion).join(
            ImageVersion,
            Image.image_id == ImageVersion.image_id
        ).filter(
            ImageVersion.admin_id == admin_id
        )

        results = query.all()

        if not results:
            return jsonify({'message': '该管理员尚未上传任何图片'}), 404

        # 构建响应数据结构
        response_data = []
        for image, version in results:
            # 处理OSS路径
            name = version.oss_path.split('mjseed-code-image/', 1)[-1]
            oss_path = f'https://mjseed-code-image.oss-cn-beijing.aliyuncs.com/{name}'

            # 组合数据
            item = {
                # 图片基本信息
                'image_id': image.image_id,
                'title': image.image_title,
                'description': image.image_description,
                'tags': [image.image_tag1, image.image_tag2, image.image_tag3],
                'vip_exclusive': image.vip_exclusive,

                # 版本信息
                'version_id': version.version_id,
                'audit_status': version.audit_status,
                'upload_time': version.upload_at.isoformat(),
                'oss_url': oss_path,

                # 管理员信息
                'uploader_id': version.admin_id,
                'uploader_type': 'super' if current_admin.admin_right == 'super' else 'normal'
            }
            response_data.append(item)

        return jsonify({
            'count': len(response_data),
            'images': response_data
        }), 200

    except Exception as e:
        return jsonify({'error': f'查询失败: {str(e)}'}), 500




#  删除照片

def delete_image(image_id):
    try:
        admin_id = 1  # 测试阶段，硬编码为1号管理员
        image = Image.query.get(image_id)
        if not image:
            return jsonify({'error': '图片不存在'}), 404



        # 删除相关版本记录
        version = ImageVersion.query.filter_by(image_id=image_id).first()
        if version:
            db.session.delete(version)

        # 拼接完整的 OSS 文件名
        filename=version.oss_path.split('mjseed-code-image/', 1)[-1]

        # 删除 OSS 中的文件
        response = bucket.delete_object(filename)


        # 删除图片记录
        db.session.delete(image)

        # 记录操作到 admin_action_db
        action = AdminAction(
            admin_id=admin_id,
            admin_operation='delete',
            operation_content=f"Deleted image with ID: {image_id}"
        )
        db.session.add(action)

        db.session.commit()
        return jsonify({'message': '删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


#  更新新的照片

def update_image(image_id):
    data = request.form
    try:
        admin_id = 1  # 测试阶段，硬编码为1号管理员
        image = Image.query.get(image_id)
        if not image:
            return jsonify({'error': '图片不存在'}), 404

        version = ImageVersion.query.filter_by(image_id=image_id).first()
        if not version:
            return jsonify({'error': '图片版本不存在'}), 404

        # 记录修改的内容
        changes = []
        if 'file' in request.files:
            # 删除旧文件
            old_filename = version.oss_path.split('mjseed-code-image/', 1)[-1]
            response = bucket.delete_object(old_filename)

            # 上传新文件
            new_file = request.files['file']
            original_filename = new_file.filename
            unique_filename = generate_unique_filename(original_filename)
            bucket.put_object(unique_filename, new_file)

            # 更新版本记录中的 oss_path
            version.oss_path = f"{bucketName}/{unique_filename}"
            changes.append(f"update at  {version.oss_path}")

        # 其他字段更新逻辑保持不变
        if 'title' in data and image.image_title != data['title']:
            changes.append(f"title from '{image.image_title}' to '{data['title']}'")
            image.image_title = data['title']
        if 'description' in data and image.image_description != data['description']:
            changes.append(f"description from '{image.image_description}' to '{data['description']}'")
            image.image_description = data['description']
        if 'resolution' in data and image.resolution != data['resolution']:
            changes.append(f"resolution from '{image.resolution}' to '{data['resolution']}'")
            image.resolution = data['resolution']
        if 'format' in data and image.format != data['format']:
            changes.append(f"format from '{image.format}' to '{data['format']}'")
            image.format = data['format']
        if 'midjourney_code' in data and image.midjourney_code != data.get('midjourney_code', {}):
            changes.append(f"midjourney_code from '{image.midjourney_code}' to '{data.get('midjourney_code', {})}'")
            image.midjourney_code = data.get('midjourney_code', {})
        if 'vip_exclusive' in data and image.vip_exclusive != data['vip_exclusive']:
            changes.append(f"vip_exclusive from '{image.vip_exclusive}' to '{data['vip_exclusive']}'")
            image.vip_exclusive = data['vip_exclusive']
        if 'tag1' in data and image.image_tag1 != data['tag1']:
            changes.append(f"tag1 from '{image.image_tag1}' to '{data['tag1']}'")
            image.image_tag1 = data['tag1']
        if 'tag2' in data and image.image_tag2 != data['tag2']:
            changes.append(f"tag2 from '{image.image_tag2}' to '{data['tag2']}'")
            image.image_tag2 = data['tag2']
        if 'tag3' in data and image.image_tag3 != data['tag3']:
            changes.append(f"tag3 from '{image.image_tag3}' to '{data['tag3']}'")
            image.image_tag3 = data['tag3']

        # 更新 image_version_db 的相关字段
        if 'oss_path' in data and version.oss_path != data['oss_path']:
            changes.append(f"oss_path from '{version.oss_path}' to '{data['oss_path']}'")
            version.oss_path = data['oss_path']
        if 'audit_status' in data and version.audit_status != data['audit_status']:
            changes.append(f"audit_status from '{version.audit_status}' to '{data['audit_status']}'")
            version.audit_status = data['audit_status']

        # 如果没有修改任何内容，返回提示
        if not changes:
            return jsonify({'message': '未修改任何内容'}), 200

        # 记录操作到 admin_action_db
        action = AdminAction(
            admin_id=admin_id,
            admin_operation='update',
            operation_content=f"Updated image with ID: {image_id}, changes: {', '.join(changes)}"
        )
        db.session.add(action)

        db.session.commit()
        return jsonify({'message': '更新成功', 'changes': changes}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500









#   对用户进行的删改查功能只有admin_right==super才能实现
#   删除用户
def delete_user(user_id):
    """
    删除用户 (Delete)
    """
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404

    try:
        # admin_id = request.headers.get('X-Admin-ID')
        # 测试阶段，硬编码为1号管理员
        admin_id = 1

        # 删除关联数据
        UserCollect.query.filter_by(user_id=user_id).delete()
        UserAction.query.filter_by(user_id=user_id).delete()

        # 删除用户
        db.session.delete(user)

        # 记录管理员操作
        action = AdminAction(
            admin_id=admin_id,
            admin_operation='delete',
            operation_content=f"DELETE user_id: {user_id}"
        )
        db.session.add(action)

        db.session.commit()
        return jsonify({'message': '用户删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        print(f"删除用户失败：{str(e)}")
        return jsonify({'error': f'删除用户失败：{str(e)}'}), 500

#   更新用户信息
@admin_required
def update_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404

    data = request.json
    changes = []
    # 从请求头中获取 X-Admin-ID
    # admin_id = request.headers.get('X-Admin-ID')
    admin_id = 1  # 测试阶段，硬编码为1号管理员
    try:
        # 更新用户名
        if 'username' in data and data['username'] != user.user_name:
            if User.query.filter_by(user_name=data['username']).first():
                return jsonify({'error': '用户名已存在'}), 409
            changes.append(f"用户名：{user.user_name} → {data['username']}")
            user.user_name = data['username']

        # 更新手机号
        if 'phone_number' in data and data['phone_number'] != user.phone_number:
            if User.query.filter_by(phone_number=data['phone_number']).first():
                return jsonify({'error': '手机号已存在'}), 409
            changes.append(f"手机号：{user.phone_number} → {data['phone_number']}")
            user.phone_number = data['phone_number']


        # 更新密码
        if 'password' in data:
            user.set_password(data['password'])
            changes.append("密码已更新")

        if changes:
            action = AdminAction(
                admin_id=admin_id,
                admin_operation='update',
                operation_content=f"update user_id: {user_id} ({'，'.join(changes)})"
            )
            db.session.add(action)

        db.session.commit()
        return jsonify({'message': '更新成功', 'changes': changes}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新失败：{str(e)}'}), 500



#   获取所有用户
@admin_required
def get_all_users():
    # 从请求头中获取 X-Admin-ID
    # admin_id = request.headers.get('X-Admin-ID')
    admin_id = 1  # 测试阶段，硬编码为1号管理员
    try:
        users = User.query.all()
        result = [{
            'user_id': u.user_id,
            'username': u.user_name,
            'phone_number': u.phone_number,
            'membership_type': u.membership_type,
            'subscription_end': u.subscription_end.isoformat() if u.subscription_end else None,
            'create_time': u.create_at.isoformat()
        } for u in users]

        return jsonify({
            'count': len(result),
            'users': result
        }), 200
    except Exception as e:
        return jsonify({'error': f'获取用户列表失败：{str(e)}'}), 500


#   获取单个用户
@admin_required
def get_single_user(user_id):
    # 从请求头中获取 X-Admin-ID
    # admin_id = request.headers.get('X-Admin-ID')
    admin_id = 1  # 测试阶段，硬编码为1号管理员
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404

    collects = UserCollect.query.filter_by(user_id=user_id).all()
    collect_data = [{
        'collect_id': c.usercollect_id,
        'name': c.collect_name,
        'item_count': CollectItem.query.filter_by(usercollect_id=c.usercollect_id).count()
    } for c in collects]

    return jsonify({
        'basic_info': {
            'user_id': user.user_id,
            'username': user.user_name,
            'phone_number': user.phone_number,
            'membership_type': user.membership_type,
            'subscription_end': user.subscription_end.isoformat() if user.subscription_end else None,
            'create_time': user.create_at.isoformat()
        },
        'collections': collect_data,
        'last_actions': [{
            'type': a.action_type,
            'image_id': a.image_id,
            'time': a.create_at.isoformat()
        } for a in UserAction.query.filter_by(user_id=user_id).order_by(UserAction.create_at.desc()).limit(5)]
    }), 200

#    可以通过user_id、user_name、phone_number其中一个查询到单一用户信息

@admin_required
def query_user():
    """
    通过user_id、user_name、phone_number查询单个用户信息
    """
    try:
        # 从请求头中获取 X-Admin-ID
        # admin_id = request.headers.get('X-Admin-ID')
        admin_id = 1  # 测试阶段，硬编码为1号管理员
        # 从请求参数中获取可能的查询条件
        user_id = request.args.get('user_id')
        user_name = request.args.get('user_name')
        phone_number = request.args.get('phone_number')

        # 确保只提供一个参数
        provided_params = [p for p in [user_id, user_name, phone_number] if p is not None]
        if len(provided_params) != 1:
            return jsonify({'error': '必须且只能提供一个查询参数（user_id、user_name或phone_number）'}), 400

        # 根据参数查询用户
        if user_id:
            if not user_id.isdigit():
                return jsonify({'error': 'user_id必须为整数'}), 400
            user = User.query.get(int(user_id))
        elif user_name:
            user = User.query.filter_by(user_name=user_name).first()
        else:
            user = User.query.filter_by(phone_number=phone_number).first()

        if not user:
            return jsonify({'error': '用户不存在'}), 404

        # 复用用户信息格式化逻辑
        return format_user_response(user)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

def format_user_response(user):
    """
    格式化用户信息响应（复用代码）
    """
    collects = UserCollect.query.filter_by(user_id=user.user_id).all()
    collect_data = [{
        'collect_id': c.usercollect_id,
        'name': c.collect_name,
        'item_count': CollectItem.query.filter_by(usercollect_id=c.usercollect_id).count()
    } for c in collects]

    return jsonify({
        'basic_info': {
            'user_id': user.user_id,
            'username': user.user_name,
            'phone_number': user.phone_number,
            'membership_type': user.membership_type,
            'subscription_end': user.subscription_end.isoformat() if user.subscription_end else None,
            'create_time': user.create_at.isoformat()
        },
        'collections': collect_data,
        'last_actions': [{
            'type': a.action_type,
            'image_id': a.image_id,
            'time': a.create_at.isoformat()
        } for a in UserAction.query.filter_by(user_id=user.user_id).order_by(UserAction.create_at.desc()).limit(5)]
    }), 200




#   VIP续费路由


# 获取所有VIP套餐
@admin_required
def get_vip_packages():
    packages = VIPPackage.query.all()
    result = [{
        'package_id': p.package_id,
        'package_type': p.package_type,
        'duration_days': p.duration_days,
        'original_price': float(p.original_price),
        'discount_rate': float(p.discount_rate),
        'is_discount_active': p.is_discount_active,
        'current_price': float(p.original_price * (1 - p.discount_rate)) if p.is_discount_active else float(
            p.original_price),
        'created_at': p.created_at.isoformat(),
        'updated_at': p.updated_at.isoformat()
    } for p in packages]
    return jsonify(result), 200


# 创建/修改VIP套餐
@admin_required
def update_vip_package():
    data = request.json
    required_fields = ['package_type', 'duration_days', 'original_price']
    if not all(f in data for f in required_fields):
        return jsonify({'error': '缺少必要参数'}), 400

    # 验证折扣率
    discount_rate = data.get('discount_rate', 0)
    if not 0 <= discount_rate <= 1:
        return jsonify({'error': '折扣率必须在0-1之间'}), 400

    # 查找或创建套餐
    package = VIPPackage.query.filter_by(package_type=data['package_type']).first()
    if not package:
        package = VIPPackage(
            package_type=data['package_type'],
            duration_days=data['duration_days'],
            original_price=data['original_price']
        )
        db.session.add(package)
        action_type = 'create'
    else:
        action_type = 'update'

    # 更新字段
    package.duration_days = data['duration_days']
    package.original_price = data['original_price']
    package.discount_rate = discount_rate
    package.is_discount_active = data.get('is_discount_active', False)

    # 记录管理员操作
    admin_id = 1  # 从请求头获取实际ID
    action = AdminAction(
        admin_id=admin_id,
        admin_operation=f'update',
        operation_content=f"{action_type} VIP package: {data['package_type']}"
    )
    db.session.add(action)

    db.session.commit()
    return jsonify({'message': '操作成功'}), 200


# 删除套餐
@admin_required
def delete_vip_package(package_id):
    package = VIPPackage.query.get(package_id)
    if not package:
        return jsonify({'error': '套餐不存在'}), 404

    db.session.delete(package)

    # 记录操作
    admin_id = 1
    action = AdminAction(
        admin_id=admin_id,
        admin_operation='delete',
        operation_content=f"Deleted VIP package: {package.package_type}"
    )
    db.session.add(action)

    db.session.commit()
    return jsonify({'message': '删除成功'}), 200













# 实际开发中应调用支付接口验证payment_id
# if not verify_payment(payment_id):
#     return {'error': '支付验证失败'}, 402

def renew_vip_service(user_id, payment_id, package_type, use_discount=False):
    """VIP续费服务（支持套餐类型）"""
    try:
        # user_id = request.headers.get('X-User-ID')
        user_id = 6 #   测试阶段使用静态id
        # ================= 根据套餐类型设置会员类型 =================
        # 定义会员类型映射逻辑（示例）
        if package_type in ['monthly', 'quarterly', 'yearly']:
            membership_type = 'premium'
        else:
            membership_type = 'member'

        # ================= 验证套餐类型 =================
        package = VIPPackage.query.filter_by(package_type=package_type).first()
        if not package:
            return {'error': '无效的套餐类型'}, 400

        # 计算实际价格
        if use_discount and package.is_discount_active:
            amount = float(package.original_price * (1 - package.discount_rate))
        else:
            amount = float(package.original_price)

        # ================= 支付验证 =================
        # if not verify_payment(payment_id):
        #     return {'error': '支付验证失败'}, 402

        # ================= 用户验证 =================
        user = User.query.get(user_id)
        if not user:
            return {'error': '用户不存在'}, 404

        # ================= VIP记录处理 =================
        vip_record = UserVIP.query.get(user_id)
        is_new_record = False

        if not vip_record:
            is_new_record = True
            vip_record = UserVIP(
                user_id=user_id,
                vip_status=membership_type,  # 使用已定义的会员类型
                renewal_count=0,
                total_duration=0
            )

        now = datetime.now()
        duration = package.duration_days

        if is_new_record:
            # 全新记录初始化
            vip_record.start_date = now
            vip_record.end_date = now + timedelta(days=duration)  # 使用 package.duration_days
            vip_record.renewal_count = 1
            vip_record.total_duration = duration
        else:
            # 续费逻辑
            if vip_record.end_date and vip_record.end_date > now:
                vip_record.end_date += timedelta(days=duration)  # 使用 package.duration_days
            else:
                vip_record.start_date = now
                vip_record.end_date = now + timedelta(days=duration)  # 使用 package.duration_days

        # ================= 更新字段 =================
        vip_record.last_renewal_date = now
        vip_record.vip_status = membership_type  # 使用已定义的变量
        user.membership_type = membership_type    # 使用已定义的变量
        user.subscription_end = vip_record.end_date

        # ================= 提交事务 =================
        db.session.add(vip_record)
        db.session.add(user)
        db.session.commit()

        # ================= 验证更新 =================
        db.session.refresh(user)
        if user.membership_type != membership_type:  # 使用已定义的变量
            raise ValueError("用户会员类型更新失败")
        if user.subscription_end != vip_record.end_date:
            raise ValueError("用户有效期更新失败")

        return {
            'message': '续费成功',
            'package_type': package_type,
            'duration_days': duration,
            'amount_charged': amount,
            'end_date': vip_record.end_date.isoformat()
        }, 200

    except Exception as e:
        db.session.rollback()
        return {'error': f'续费失败: {str(e)}'}, 500


def verify_payment(payment_id):
    """
    支付验证函数（示例实现）
    实际开发中需替换为真实支付平台接口调用
    """
    # 示例：调用支付平台API验证payment_id
    try:
        # 这里以模拟支付接口为例，真实环境替换为实际API地址
        response = requests.get(
            f"https://api.payment-gateway.com/verify/{payment_id}",
            timeout=10
        )
        # 假设返回状态码200表示验证成功
        return response.status_code == 200
    except requests.exceptions.RequestException as e:
        # 处理网络错误
        print(f"支付接口调用失败: {str(e)}")
        return False





# ================== 在 admin_backend.py 中添加以下函数 ==================

# 创建管理员
@admin_required
def create_admin():
    """
    创建管理员 (POST)
    Request JSON示例:
    {
        "admin_name": "admin2",
        "password": "Admin@123",
        "phone": "13800138000",
        "rights": "normal"
    }
    """
    data = request.json
    required_fields = ['admin_name', 'password', 'phone']
    if not all(field in data for field in required_fields):
        return jsonify({'error': '缺少必要参数'}), 400

    # 获取当前操作的管理员
    # current_admin_id = request.headers.get('X-Admin-ID')
    current_admin_id = 1  # 测试阶段硬编码
    current_admin = Admin.query.get(current_admin_id)


    try:
        # 检查用户名和手机号是否已存在
        if Admin.query.filter_by(admin_name=data['admin_name']).first():
            return jsonify({'error': '用户名已存在'}), 409
        if Admin.query.filter_by(admin_phone_number=data['phone']).first():
            return jsonify({'error': '手机号已存在'}), 409

        # 创建管理员
        new_admin = Admin(
            admin_name=data['admin_name'],
            admin_phone_number=data['phone'],
            admin_right='normal'
        )
        # 设置密码
        new_admin.admin_password = argon2.hash(data['password'])  # 使用与用户相同的加密方式

        db.session.add(new_admin)

        # 记录管理员操作
        action = AdminAction(
            admin_id=current_admin_id,
            admin_operation='create',
            operation_content=f"Created admin: {data['admin_name']}"
        )
        db.session.add(action)

        db.session.commit()
        return jsonify({'admin_id': new_admin.admin_id}), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 删除管理员
@admin_required
def delete_admin(admin_id):
    """
    删除管理员 (DELETE)
    """
    # 获取当前操作的管理员
    # current_admin_id = request.headers.get('X-Admin-ID')
    current_admin_id = 1  # 测试阶段硬编码
    current_admin = Admin.query.get(current_admin_id)

    try:
        # 权限验证：只有超级管理员可以删除
        if current_admin.admin_right != 'super':
            return jsonify({'error': '权限不足'}), 403

        # 不能删除自己
        if admin_id == current_admin_id:
            return jsonify({'error': '不能删除自己'}), 400

        target_admin = Admin.query.get(admin_id)
        if not target_admin:
            return jsonify({'error': '管理员不存在'}), 404

        # 执行删除
        db.session.delete(target_admin)

        # 记录操作
        action = AdminAction(
            admin_id=current_admin_id,
            admin_operation='delete',
            operation_content=f"Deleted admin: {target_admin.admin_name}"
        )
        db.session.add(action)

        db.session.commit()
        return jsonify({'message': '管理员删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@admin_required
def update_admin(admin_id):
    """
    修改管理员信息 (PUT)
    Request JSON示例:
    {
        "admin_name": "new_name",
        "phone": "13800138001",
        "rights": "super",
        "password": "NewPass123"
    }
    """
    # 获取当前操作的管理员
    # current_admin_id = request.headers.get('X-Admin-ID')
    current_admin_id = 1  # 测试阶段硬编码
    current_admin = Admin.query.get(current_admin_id)
    target_admin = Admin.query.get(admin_id)

    # 基础验证
    if not target_admin:
        return jsonify({'error': '目标管理员不存在'}), 404

    data = request.json
    changes = []

    try:
        # # 权限验证逻辑
        # if current_admin.admin_right != 'super' and admin_id != current_admin_id:
        #     return jsonify({'error': '只能修改自己的信息'}), 403

        # 字段更新逻辑
        # 1. 修改用户名
        if 'admin_name' in data and data['admin_name'] != target_admin.admin_name:
            if Admin.query.filter(Admin.admin_name == data['admin_name']).first():
                return jsonify({'error': '用户名已存在'}), 409
            changes.append(f"用户名: {target_admin.admin_name} → {data['admin_name']}")
            target_admin.admin_name = data['admin_name']

        # 2. 修改手机号
        if 'phone' in data and data['phone'] != target_admin.admin_phone_number:
            if Admin.query.filter(Admin.admin_phone_number == data['phone']).first():
                return jsonify({'error': '手机号已存在'}), 409
            changes.append(f"手机号: {target_admin.admin_phone_number} → {data['phone']}")
            target_admin.admin_phone_number = data['phone']

        # 3. 修改权限（仅限超级管理员）
        if 'rights' in data:
            if current_admin.admin_right != 'super':
                return jsonify({'error': '无权修改权限等级'}), 403
            if data['rights'] not in ['super', 'normal']:
                return jsonify({'error': '无效的权限类型'}), 400
            changes.append(f"权限: {target_admin.admin_right} → {data['rights']}")
            target_admin.admin_right = data['rights']

        # 4. 修改密码
        if 'password' in data:
            if admin_id != current_admin_id and current_admin.admin_right != 'super':
                return jsonify({'error': '无权修改他人密码'}), 403
            target_admin.set_password(data['password'])
            changes.append("密码已更新")

        # 如果没有修改内容
        if not changes:
            return jsonify({'message': '未修改任何内容'}), 200

        # 记录操作日志
        action = AdminAction(
            admin_id=current_admin_id,
            admin_operation='update',
            operation_content=f"修改管理员 {admin_id}：" + "，".join(changes)
        )
        db.session.add(action)

        db.session.commit()
        return jsonify({'message': '修改成功', 'changes': changes}), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'修改失败: {str(e)}'}), 500




# 获取所有管理员
@admin_required
def get_admins():
    """
    获取管理员列表 (GET)
    返回数据示例：
    {
        "admins": [
            {
                "admin_id": "1",
                "admin_name": "superadmin",
                "phone": "13800000000",
                "rights": "super",
                "create_time": "2023-07-20T10:00:00"
            }
        ]
    }
    """
    try:
        # 获取当前管理员
        # current_admin_id = request.headers.get('X-Admin-ID')
        current_admin_id = 1  # 测试阶段硬编码
        current_admin = Admin.query.get(current_admin_id)

        # 普通管理员只能查看普通管理员列表
        if current_admin.admin_right == 'normal':
            admins = Admin.query.filter_by(admin_right='normal').all()
        else:  # 超级管理员查看全部
            admins = Admin.query.all()

        result = [{
            'admin_id': a.admin_id,
            'admin_name': a.admin_name,
            'phone': a.admin_phone_number,
            'rights': a.admin_right,
        } for a in admins]

        return jsonify({'admins': result}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

#查询单个管理员（通过手机或者名字）
@admin_required
def query_admin():
    """
    通过 admin_name 或 admin_phone_number 查询单个管理员信息
    """
    try:
        admin_name = request.args.get('admin_name')
        admin_phone_number = request.args.get('admin_phone_number')

        # 确保只提供一个查询参数
        provided_params = [p for p in [admin_name, admin_phone_number] if p is not None]
        if len(provided_params) != 1:
            return jsonify({'error': '必须且只能提供一个查询参数（admin_name 或 admin_phone_number）'}), 400

        # 根据提供的参数查询管理员
        if admin_name:
            admin = Admin.query.filter_by(admin_name=admin_name).first()
        else:
            admin = Admin.query.filter_by(admin_phone_number=admin_phone_number).first()

        if not admin:
            return jsonify({'error': '管理员不存在'}), 404

        # 组织返回结果
        return jsonify({
            'admin_id': admin.admin_id,
            'admin_name': admin.admin_name,
            'phone': admin.admin_phone_number,
            'rights': admin.admin_right
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500
